from elasticsearch import Elasticsearch

from ES_utils import es_config



def getClient() -> Elasticsearch:
    client = Elasticsearch(*es_config.ES_CONFIG_ARGS, **es_config.ES_CONFIG_KARGS)
    return client

def forwardRequest(json_data:dict) -> dict:
    """
    forward request to elasticsearch server from frontend
    """
    index_url, json_data = searchFilterForPost(json_data)
    client = getClient()
    res = client.search(index=index_url, body=json_data)
    return return_filter(res)

def return_filter(json_data:dict) -> dict:
    """
    filter return data
    """
    return json_data["hits"]["hits"]

    
def searchFilterForPost(json_data):
    """
    parse target index, filter safe data.
    
    return: 
        index: str, json_data: dict
    raise TypeError when json not valid
    """
    

    ALLOWED_OP_TARGET = ['paper', 'author', 'venue']
    
    json_data_out = {}
    index = ""
    _op_target = json_data['_op_target']

    if _op_target in ALLOWED_OP_TARGET:
        index+=_op_target
        pass
    else:
        raise TypeError('invalid _op_target: {}'.format(_op_target))
        pass

    _op_type = json_data['_op_type']

    ALLOWED_OP_TYPE = ['_search', ]
    if _op_type in ALLOWED_OP_TYPE:
        # index+= "/"+_op_type
        pass
    else:
        raise TypeError('invalid _op_type: {}'.format(_op_type))
        pass
    # 放行query
    if json_data.get('query'):
        json_data_out['query'] = json_data['query']
    else:
        raise TypeError('invalid query')
        pass

    # 放行sort
    if json_data.get('sort'):
        json_data_out['sort'] = json_data['sort']
    else:
        
        pass

    # 放行size<=100,>=0
    if json_data.get('size'):
        if json_data['size']<=100 and json_data['size']>=0:
            json_data_out['size'] = json_data['size']
        else:
            raise TypeError('invalid size: {}'.format(json_data['size']))
            pass
    
    # 放行from
    if json_data.get('from'):
        json_data_out['from'] = json_data['from']
    else:
        pass

    # 放行_source
    if json_data.get('_source'):
        json_data_out['_source'] = json_data['_source']
    else:
        pass

    # 放行must_not
    if json_data.get('must_not'):
        json_data_out['must_not'] = json_data['must_not']
    else:
        pass

    # 放行highlight
    if json_data.get('highlight'):
        json_data_out['highlight'] = json_data['highlight']
    else:
        pass
    
    return index, json_data_out

